package com.hnjfzn.message.sms.controller;

import com.hnjfzn.common.core.context.SecurityContextHolder;
import com.hnjfzn.common.core.exception.sms.SmsException;
import com.hnjfzn.common.core.utils.StringUtils;
import com.hnjfzn.common.core.web.domain.AjaxResult;
import com.hnjfzn.message.sms.domain.enums.SmsPlatformType;
import com.hnjfzn.message.sms.service.ISmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import static com.hnjfzn.common.core.constant.SmsConstants.*;

/**
 * 短信服务
 */
@RestController
public class SmsController {

    @Autowired
    private ISmsService smsService;

    private void def(String sign, SmsPlatformType platform) {
        SecurityContextHolder.set(SMS_PLATFORM_KEY, null == platform ? SmsPlatformType.ALI : platform);
        SecurityContextHolder.set(SMS_SIGN_KEY, StringUtils.isEmpty(sign) ? SMS_SIGN : sign);
    }

    @GetMapping("/captcha")
    public AjaxResult captcha(@RequestParam("phone") String phone, @RequestParam(value = "sign", required = false) String sign, @RequestParam(value = "platform", required = false) SmsPlatformType platform)  {
        def(sign, platform);
        // 手机号校验
        if (StringUtils.isEmpty(phone)) {
            return AjaxResult.error("请输入手机号");
        }
        // 手机号格式校验
        if (!phone.matches("^1[3-9]\\d{9}$")) {
            return AjaxResult.error("请输入正确的手机号");
        }
        try{
            Long smsId = smsService.sendCaptcha(phone);
            if (null != smsId) {
                AjaxResult ajaxResult = AjaxResult.success();
                ajaxResult.put("uuid", String.valueOf(smsId));
                return ajaxResult;
            }
        } catch (SmsException e) {
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.error("发送失败");
    }
}
